package com.shanzhu.beadhouse.service.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shanzhu.beadhouse.dao.mapper.SetDishesMapper;
import com.shanzhu.beadhouse.entity.po.SetDishes;
import com.shanzhu.beadhouse.entity.query.OperateCateringSetQuery;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;

import javax.annotation.Resource;
import java.util.*;

@Component
public class SetDishesFunc extends ServiceImpl<SetDishesMapper, SetDishes> {
    @Resource
    private SetDishesMapper setDishesMapper;

    /**
     * 批量保存套餐菜品关系（新版）
     */
    public void saveBatchSetDishes(OperateCateringSetQuery query, Long setId) {
        if (query.getMealPlans() == null) {
            return;
        }

        // 删除该套餐原有的菜品关联
        setDishesMapper.delete(new LambdaQueryWrapper<SetDishes>()
                .eq(SetDishes::getSetId, setId));

        List<SetDishes> setDishesList = new ArrayList<>();
        query.getMealPlans().forEach((weekDay, mealMap) -> {
            mealMap.forEach((mealTime, dishesIds) -> {
                dishesIds.forEach(dishesId -> {
                    SetDishes sd = new SetDishes();
                    sd.setSetId(setId);
                    sd.setDishesId(dishesId);
                    sd.setWeekDay(weekDay);
                    sd.setMealTime(mealTime);
                    sd.setCreateId(query.getCreateId());
                    sd.setCreateTime(new Date());
                    sd.setUpdateId(query.getUpdateId());
                    sd.setUpdateTime(new Date());
                    setDishesList.add(sd);
                });
            });
        });

        saveBatchSetDishes(setDishesList);
    }

    /**
     * 基础批量保存方法
     */
    public void saveBatchSetDishes(List<SetDishes> setDishesList) {
        if (CollectionUtils.isEmpty(setDishesList)) {
            return;
        }

        // 分批插入（每批200条）
        List<List<SetDishes>> partitions = Lists.partition(setDishesList, 200);
        partitions.forEach(partition -> {
            setDishesMapper.batchInsert(partition);
        });
    }
}